package com.edu.servlet;

import com.edu.bean.CampusStyle;
import com.edu.service.AdminCampusStyleService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/admin/campus/*")
public class AdminCampusStyleServlet extends HttpServlet {
    private AdminCampusStyleService adminCampusStyleService = new AdminCampusStyleService();
    private static final String UPLOAD_DIRECTORY = "upload/campus";
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/list":
                listCampusStyle(request, response);
                break;
            case "/get":
                getCampusStyle(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/add":
                addCampusStyle(request, response);
                break;
            case "/update":
                updateCampusStyle(request, response);
                break;
            case "/delete":
                deleteCampusStyle(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private void listCampusStyle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取分页参数
        int pageSize = 10; // 每页显示10条
        int currentPage = 1; // 默认第一页
        String pageStr = request.getParameter("page");
        if (pageStr != null && !pageStr.trim().isEmpty()) {
            try {
                currentPage = Integer.parseInt(pageStr);
                if (currentPage < 1) {
                    currentPage = 1;
                }
            } catch (NumberFormatException e) {
                // 解析失败，使用默认值
            }
        }

        // 获取搜索参数
        String title = request.getParameter("title");

        // 获取总记录数和总页数
        int totalCount = adminCampusStyleService.adminGetTotalCount(title);
        int totalPages = (totalCount + pageSize - 1) / pageSize;

        // 校正当前页码
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }
        if (currentPage < 1) {
            currentPage = 1;
        }

        // 获取当前页的数据
        List<CampusStyle> styleList = adminCampusStyleService.adminListCampusStyleByPage(title, currentPage, pageSize);

        // 设置分页相关的属性
        request.setAttribute("styleList", styleList);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("title", title);

        request.getRequestDispatcher("/admin/campus-list.jsp").forward(request, response);
    }

    private void getCampusStyle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.trim().isEmpty()) {
            CampusStyle style = adminCampusStyleService.adminGetCampusStyle(Integer.parseInt(idStr));
            if (style != null) {
                request.setAttribute("style", style);
                request.getRequestDispatcher("/admin/campus-edit.jsp").forward(request, response);
                return;
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            request.getRequestDispatcher("/admin/campus-add.jsp").forward(request, response);
        }
    }

    private void addCampusStyle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = upload.parseRequest(request);
            CampusStyle style = new CampusStyle();
            String imageUrl = null;

            for (FileItem item : items) {
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString("UTF-8");

                    switch (fieldName) {
                        case "title":
                            style.setTitle(fieldValue);
                            break;
                        case "description":
                            style.setDescription(fieldValue);
                            break;
                        case "status":
                            style.setStatus(Integer.parseInt(fieldValue));
                            break;
                    }
                } else {
                    if (item.getSize() > 0) {
                        String fileName = UUID.randomUUID().toString() +
                                item.getName().substring(item.getName().lastIndexOf("."));
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        item.write(storeFile);
                        imageUrl = UPLOAD_DIRECTORY + "/" + fileName;
                    }
                }
            }

            if (imageUrl != null) {
                style.setImageUrl(imageUrl);
            }

            boolean success = adminCampusStyleService.adminAddCampusStyle(style);
            result.put("success", success);
            if (!success) {
                result.put("message", "添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void updateCampusStyle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = upload.parseRequest(request);
            CampusStyle style = new CampusStyle();
            String imageUrl = null;

            for (FileItem item : items) {
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString("UTF-8");

                    switch (fieldName) {
                        case "styleId":
                            style.setStyleId(Integer.parseInt(fieldValue));
                            break;
                        case "title":
                            style.setTitle(fieldValue);
                            break;
                        case "description":
                            style.setDescription(fieldValue);
                            break;
                        case "status":
                            style.setStatus(Integer.parseInt(fieldValue));
                            break;
                    }
                } else {
                    if (item.getSize() > 0) {
                        String fileName = UUID.randomUUID().toString() +
                                item.getName().substring(item.getName().lastIndexOf("."));
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        item.write(storeFile);
                        imageUrl = UPLOAD_DIRECTORY + "/" + fileName;
                    }
                }
            }

            if (imageUrl != null) {
                style.setImageUrl(imageUrl);
            }

            boolean success = adminCampusStyleService.adminUpdateCampusStyle(style);
            result.put("success", success);
            if (!success) {
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void deleteCampusStyle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.trim().isEmpty()) {
            boolean success = adminCampusStyleService.adminDeleteCampusStyle(Integer.parseInt(idStr));
            result.put("success", success);
            if (!success) {
                result.put("message", "删除失败");
            }
        } else {
            result.put("success", false);
            result.put("message", "参数错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }
}